home *** CD-ROM | disk | FTP | other *** search
/ Programming Languages Suite / ProgramD2.iso / Borland / Borland C++ V5.02 / STDLIB.PAK / FUNCT_OB.CPP < prev    next >
C/C++ Source or Header  |  1997-05-06  |  1KB  |  57 lines

  1.  #include <functional>
  2.  #include <deque>
  3.  #include <vector>
  4.  #include <algorithm>
  5.  
  6.  using namespace std;
  7.  
  8.  //
  9.  // Create a new function object from unary_function.
  10.  //
  11.  template<class Arg>
  12.  class factorial : public unary_function<Arg, Arg>
  13.  {
  14.    public:
  15.      Arg operator() (const Arg& arg);
  16.  };
  17.  
  18.  template<class Arg>
  19.  Arg factorial<Arg>::operator() (const Arg& arg)
  20.  {
  21.     Arg a = 1;
  22.     for (Arg i = 2; i <= arg; i++)
  23.     a *= i;
  24.     return a;
  25.  }
  26.  
  27.  
  28.  
  29.  int main ()
  30.  {
  31.    //
  32.    // Initialize a deque with an array of integers.
  33.    //
  34.    int init[7] = {1,2,3,4,5,6,7};
  35.    deque<int> d(init+0, init+7);
  36.    //
  37.    // Create an empty vector to store the factorials.
  38.    //
  39.    vector<int> v((size_t)7);
  40.    //
  41.    // Transform the numbers in the deque to their factorials and store
  42.    // in the vector.
  43.    //
  44.    transform(d.begin(), d.end(), v.begin(), factorial<int>());
  45.    //
  46.    // Print the results.
  47.    //
  48.    cout << "The following numbers: " << endl << "     ";
  49.    copy(d.begin(), d.end(), ostream_iterator<int>(cout," "));
  50.  
  51.    cout << endl << endl;
  52.    cout << "Have the factorials: " << endl << "     ";
  53.    copy(v.begin(), v.end(), ostream_iterator<int>(cout," "));
  54.  
  55.    return 0;
  56.  }
  57.